package com.zhizuobiao.class4;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/8/4 0004.
 */
public class CglibProxy {

    private AdminDao dao;

    public CglibProxy(AdminDao dao) {
        this.dao = dao;
    }

    public AdminDao getProxy() {
        Enhancer enhancer = new Enhancer();
        // 设置代理类的class
        enhancer.setSuperclass(dao.getClass());

        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                // 在执行原方法前，添加增强代码
                System.out.println("DBUtil.openCollection()");

                Object result = method.invoke(dao, objects);

                // 在执行原方法后，添加增强代码
                System.out.println("DBUtil.close(Collection conn)");


                return result;
            }
        });
        // 生成代理对象
        return (AdminDao) enhancer.create();
    }
}
